package com.lbssoft.datalink.util;

import java.io.IOException;

import com.lbssoft.datalink.model.Property;
import org.apache.log4j.Appender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;


public final class Log {

    private Log() {
    }

    public static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static final String NAME = "DataLink";

    private static Logger logger = null;

    public static void setupLog(Property property) throws IOException {
        String file = "./logs/datalink.log";
        if (property.getLogFile() != null) {
            file = property.getLogFile();
        }
        Appender appender = new DailyRollingFileAppender(new PatternLayout("%d{" + DATE_FORMAT + "} %5p: %m%n"), file, "'.'yyyyMMdd");


        logger = Logger.getLogger(NAME);
        logger.addAppender(appender);
        logger.setLevel(Level.toLevel(property.getLogLevel(), Level.ALL));
        Log.info("************************************");
        Log.info("名称：DataLink-SDK");
        Log.info("版本：v1.1.4");
        Log.info("Copyright:Copyright (C) 2014-2018");
        Log.info("Cpmpany:安徽东位信息科技有限责任公司");
        Log.info("All Rights Reserved");
        Log.info("************************************");
    }

    public static Logger getLog() {
        if (logger == null) {
            logger = Logger.getLogger(NAME);
            logger.setLevel(Level.OFF);
        }
        return logger;
    }


    public static void info(String msg) {
        getLog().info(msg);

    }

    public static void debug(String msg) {
        getLog().debug(msg);

    }

    public static void warning(Throwable exception) {
        warning(null, exception);

    }

    public static void warning(String msg, Throwable exception) {
        StringBuilder sb = new StringBuilder();
        if (msg != null) {
            sb.append(msg);
        }
        if (exception != null) {
            if (msg != null) {
                sb.append(" -- ");
            }
            sb.append(exceptionStack(exception));
        }
        getLog().warn(sb.toString());
    }


    public static String exceptionStack(Throwable exception) {
        StringBuilder sb = new StringBuilder();
        String exceptionMsg = exception.getMessage();
        if (exceptionMsg != null) {
            sb.append(exceptionMsg);
        }
        return sb.toString();
    }

}
